<?php

namespace App\Models\Factory;

use App\Helpers\DateUtils;
use App\Helpers\Http\HttpClient;
use App\Helpers\Utils;
use App\Models\AbsModelFactory;
use App\Models\Orm\CoinLog;
use App\Models\Orm\InviteUser;
use App\Models\Orm\Sign;
use App\Models\Orm\SmsConfig;
use App\Models\Orm\SystemConfig;
use App\Models\Orm\User;
use App\Models\Orm\UserIncome;
use App\Strategies\SmsStrategy;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * 短信工厂
 * Class SmsFactory
 * @package App\Models\Factory
 */
class InviteFactory extends AbsModelFactory
{
    //插入邀请关系表
    public static function addInviteUser($userId,$invite_user_id)
    {
        $data['user_id'] = $userId;
        $data['pid'] = $invite_user_id;
        return InviteUser::create($data);
    }

    //赠送直接金币
    public static function addUserIncome($userId,$income)
    {
        $userIncomObj = UserIncome::where('user_id',$userId)->first();
        $userIncomObj -> person_income += $income;
        $userIncomObj -> person_number += 1;
        return $userIncomObj -> save();
    }


    //插入签到金币
    public static function addSignIncome($userId,$income)
    {
        $userIncomObj = UserIncome::where('user_id',$userId)->first();
        $userIncomObj -> sign_income += $income;
        return $userIncomObj -> save();
    }


    //初始化收入表

    public static function initUserIncome($userId)
    {
        $data['user_id'] = $userId;
        $data['created_at'] = DateUtils::getToday();
        return UserIncome::create($data);
    }

    //查找邀请父id
    public static function findPid($inviteCode,$income,$handle)
    {
       $pidObj = InviteUser::where('user_id',$inviteCode)->get()->toArray();
        //如果邀请人有父id,加金币
        if(count($pidObj) > 1 || $handle ==1){
            $incomeObj = UserIncome::where('user_id',$pidObj[1]['pid'])->first();
            $incomeObj -> team_number += 1;
            $incomeObj -> team_income += $income;
            $incomeResult = $incomeObj -> save();

            $user = User::where('id',$pidObj[1]['pid'])->first();
            $user -> total += $income;
            $user -> save();

            if($incomeResult ){
                // 递归
                $result = self::findPid($pidObj[1]['pid'],$income = UserIncome::THIRDINCOME,$handle=1);
                return $result ? true : false;
            }

            return false;
        }else{
            return true;
        }

    }

    //通过用户id查到pid
    public static function getPid($userId)
    {
       $result =  InviteUser::where('user_id',$userId)->first();
        return $result ? $result : "";
    }



}